#include "buzzer.h"

static uint8_t buzzerState;

static void buzzer_gpio_init(void)
{
    rcu_periph_clock_enable(RCU_GPIOA);
    rcu_periph_clock_enable(RCU_AF);
    gpio_pin_remap_config(GPIO_SWJ_SWDPENABLE_REMAP,ENABLE);
    gpio_pin_remap_config(GPIO_TIMER1_PARTIAL_REMAP0, ENABLE);
    gpio_init(GPIOA, GPIO_MODE_AF_PP, GPIO_OSPEED_50MHZ, GPIO_PIN_15);
}

static void buzzer_timer_init(void)
{
    timer_parameter_struct timerInitStruct;
    timer_oc_parameter_struct timerOcStruct;

    rcu_periph_clock_enable(RCU_TIMER1);
    timerInitStruct.prescaler = (SystemCoreClock / 4 / 1000000) - 1;
    timerInitStruct.alignedmode = TIMER_COUNTER_EDGE;
    timerInitStruct.counterdirection = TIMER_COUNTER_UP;
    timerInitStruct.period = 1000 - 1;
    timerInitStruct.clockdivision = TIMER_CKDIV_DIV4;
    timerInitStruct.repetitioncounter = 0;
    timer_init(TIMER1, &timerInitStruct);
    timerOcStruct.outputstate = TIMER_CCX_ENABLE;
    timerOcStruct.outputnstate = TIMER_CCXN_DISABLE;
    timerOcStruct.ocpolarity = TIMER_OC_POLARITY_HIGH;
    timerOcStruct.ocnpolarity = TIMER_OCN_POLARITY_HIGH;
    timerOcStruct.ocidlestate = TIMER_OC_IDLE_STATE_LOW;
    timerOcStruct.ocnidlestate = TIMER_OCN_IDLE_STATE_LOW;
    timer_channel_output_config(TIMER1, TIMER_CH_0, &timerOcStruct);

    timer_channel_output_pulse_value_config(TIMER1,TIMER_CH_0, 500 - 1);
    timer_channel_output_mode_config(TIMER1,TIMER_CH_0,TIMER_OC_MODE_PWM0);
    timer_channel_output_shadow_config(TIMER1, TIMER_CH_0, TIMER_OC_SHADOW_DISABLE);

    timer_auto_reload_shadow_enable(TIMER1);
    timer_channel_output_state_config(TIMER1, TIMER_CH_0, TIMER_CCX_DISABLE);
    timer_enable(TIMER1);
}

void buzzer_set(uint8_t state)
{
    if(buzzerState != state)
    {
        buzzerState = state;
        if(state)
        {
            timer_channel_output_state_config(TIMER1, TIMER_CH_0, TIMER_CCX_ENABLE);
        }
        else	
        {
            timer_channel_output_state_config(TIMER1, TIMER_CH_0, TIMER_CCX_DISABLE);
        }
    }
}

void buzzer_init(void)
{
    buzzer_gpio_init();
    buzzer_timer_init();
}


